const express = require('express');
const app = express();
const session = require('express-session')
const morgan = require('morgan');//打印日志
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

//const bluebird=require('bluebird');解决异步回调

const url = 'mongodb://localhost:27017/node'
//'mongodb://yyp:y15807075503@cluster0-shard-00-00-s41ol.mongodb.net:27017,cluster0-shard-00-01-s41ol.mongodb.net:27017,cluster0-shard-00-02-s41ol.mongodb.net:27017/node?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true';


mongoose.connect(url, { useNewUrlParser: true })
//mongoose.Promise = global.Promise;

app.use(morgan('dev'));
app.use("/uploads", express.static('uploads'))//设置静态文件路径
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
    secret: 'yyp-secret-key',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 1000*60 }//*60*24*1登录有效期1小时
}))
app.use((req, res, next) => {//跨域访问处理
    /** var orginList=[
        "http://bd:3000",
        //"http://127.0.0.1:35636",
        "http://localhost:3000"
    ]//设置允许跨域的域名
    if(orginList.includes(req.headers.origin.toLowerCase())){
        res.header("Access-Control-Allow-Origin",req.headers.origin);
    }
    */
    res.header('Access-Control-Allow-Origin', "*");//*代表允许任意域名跨域
    res.header('Access-Control-Allow-Headers', "Origin,X-Ruqested-Width,Content-Type,Accpet,Authorization");
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,PATCH');
        /*return res.status(200).json({})*/
    }
    next();
})
const productRoute = require('./api/routes/product');
const userRoute = require('./api/routes/user');
const orderRoute = require('./api/routes/order');
const wxRoute = require('./api/routes/weixin');

app.use("/product", productRoute);
app.use("/order", orderRoute);
app.use("/user", userRoute);
app.use("/weixin", wxRoute);


app.use((req, res, next) => {
    const error = new Error('not found');
    error.status = 404;
    next(error)
})
app.use((error, req, res, next) => {
    res.status(error || 500)
    res.json({
        error: {
            message: error.message
        }
    })
})


//app.listen(process.env.PROT)
module.exports = app;